const jwt = require('jsonwebtoken');

// JWT密钥配置
const JWT_SECRET = process.env.JWT_SECRET || 'your-super-secret-jwt-key-change-in-production';
const JWT_REFRESH_SECRET = process.env.JWT_REFRESH_SECRET || 'your-super-secret-refresh-key-change-in-production';

// Token过期时间配置
const ACCESS_TOKEN_EXPIRES_IN = '15m'; // 15分钟
const REFRESH_TOKEN_EXPIRES_IN = '7d'; // 7天

// 生成访问令牌
const generateAccessToken = (payload) => {
    return jwt.sign(payload, JWT_SECRET, {
        expiresIn: ACCESS_TOKEN_EXPIRES_IN,
        issuer: 'school-management-system'
    });
};

// 生成刷新令牌
const generateRefreshToken = (payload) => {
    return jwt.sign(payload, JWT_REFRESH_SECRET, {
        expiresIn: REFRESH_TOKEN_EXPIRES_IN,
        issuer: 'school-management-system'
    });
};

// 生成双token
const generateTokenPair = (user) => {
    const payload = {
        userId: user.id,
        username: user.username,
        role: user.role,
        phone: user.phone
    };

    return {
        accessToken: generateAccessToken(payload),
        refreshToken: generateRefreshToken(payload),
        expiresIn: 15 * 60 * 1000 // 15分钟，毫秒
    };
};

// 验证访问令牌
const verifyAccessToken = (token) => {
    try {
        return jwt.verify(token, JWT_SECRET);
    } catch (error) {
        throw new Error('Invalid access token');
    }
};

// 验证刷新令牌
const verifyRefreshToken = (token) => {
    try {
        return jwt.verify(token, JWT_REFRESH_SECRET);
    } catch (error) {
        throw new Error('Invalid refresh token');
    }
};

// 刷新访问令牌
const refreshAccessToken = (refreshToken) => {
    const decoded = verifyRefreshToken(refreshToken);
    return generateAccessToken({
        userId: decoded.userId,
        username: decoded.username,
        role: decoded.role,
        phone: decoded.phone
    });
};

module.exports = {
    generateTokenPair,
    verifyAccessToken,
    verifyRefreshToken,
    refreshAccessToken,
    generateAccessToken,
    generateRefreshToken
};
